﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using Mall.Model;
using Serialize.Library;
using System;
using System.Collections.Generic;

namespace Mall.Logic
{
    /// <summary>
    /// 商品信息操作类
    /// </summary>
    public class GoodsInfoServiceImpl : OperationLogicImpl, IGoodsInfoService
    {
        #region 商品信息基础管理模块

        #region 查询

        /// <summary>
        /// 根据关键字分页获取列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<GoodsInfoResponse>> LoadPageList(ParametersInfo<GoodsInfoQuery> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<GoodsInfoResponse>>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                int isDeleted = (int)IsDeleted.Deleted;
                var result = con.QuerySet<View_GoodsInfoEntity>().Where(a => a.is_deleted != isDeleted);
                if (inputInfo.parameters.category_id.IsNotNullOrEmpty())
                {
                    result.Where(p => p.category_id.Equals(inputInfo.parameters.category_id));
                }
                if (inputInfo.parameters.keywords.IsNotNullOrEmpty())
                {
                    result.Where(p => p.name.Contains(inputInfo.parameters.keywords)
                    || p.title.Contains(inputInfo.parameters.keywords)
                    || p.goods_no.Contains(inputInfo.parameters.keywords)
                    );
                }

                #region 排序
                if (inputInfo.field.IsNullOrEmpty())
                {
                    inputInfo.field = " sort";
                }
                if (inputInfo.order.IsNullOrEmpty())
                {
                    inputInfo.order = " asc";
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                #endregion

                var queryInfo = result.PageList(inputInfo.page, inputInfo.limit, p => new View_GoodsInfoEntity
                {
                    id = p.id,
                    category_id = p.category_id,
                    category_name = p.category_name,
                    name = p.name,
                    title = p.title,
                    goods_no = p.goods_no,
                    selling_price = p.selling_price,
                    original_price = p.original_price,
                    is_hot_style = p.is_hot_style,
                    is_new_style = p.is_new_style,
                    is_recommend = p.is_recommend,
                    is_bargain = p.is_bargain,
                    is_shelves = p.is_shelves,
                    sales_volume = p.sales_volume,
                    create_time = p.create_time
                });

                if (queryInfo.Items.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = queryInfo.Items.MapToList<GoodsInfoResponse>();
                    resultInfo.Count = queryInfo.Total;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据id获取对应的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<GoodsInfoResponse> LoadSingleById(string id)
        {
            var resultInfo = new ResultJsonInfo<GoodsInfoResponse>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                int isDeleted = (int)FlowStatus.Deleted;
                var result = con.QuerySet<View_GoodsInfoEntity>()
                    .Where(p => p.is_deleted != isDeleted && p.id.Equals(id)).Get();
                if (result != null)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result.MapTo<GoodsInfoResponse>();
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据商品id获取附件文件
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<GoodsPictureEntity>> LoadAttachList(string goodsId)
        {

            var resultInfo = new ResultJsonInfo<List<GoodsPictureEntity>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var listInfo = con.QuerySet<GoodsPictureEntity>()
                        .Where(a => a.goods_id.Equals(goodsId))
                        .OrderBy(p => p.sort)
                        .ToList();

                if (listInfo.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                }
                else
                {
                    resultInfo.Data = new List<GoodsPictureEntity>();
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据id获取对应的详情信息【基本信息+附件】
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<GoodsDetailResponse> LoadDetailById(string id)
        {
            var resultInfo = new ResultJsonInfo<GoodsDetailResponse>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                int isDeleted = (int)FlowStatus.Deleted;
                var result = con.QuerySet<View_GoodsInfoEntity>()
                    .Where(p => p.is_deleted != isDeleted && p.id.Equals(id)).Get();
                if (result != null)
                {
                    var pictures = con.QuerySet<GoodsPictureEntity>()
                       .Where(a => a.goods_id.Equals(id))
                       .OrderBy(p => p.sort)
                       .ToList();

                    resultInfo.Data = new GoodsDetailResponse();
                    if (pictures.Count > 0)
                    {
                        resultInfo.Data.fileInfo  = pictures;
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data.baseInfo = result.MapTo<GoodsInfoResponse>();
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }

        #endregion

        #region 更新

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> SaveInfo(GoodsInfoModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;
                if (inputInfo.id.IsNotNullOrEmpty())
                {
                    #region Modify
                    var modifyInfo = con.QuerySet<GoodsInfoEntity>().Where(p => p.id == inputInfo.id).Get();
                    if (modifyInfo != null)
                    {
                        modifyInfo.category_id = inputInfo.category_id;
                        modifyInfo.name = inputInfo.name;
                        modifyInfo.title = inputInfo.title;
                        modifyInfo.goods_no = inputInfo.goods_no;
                        modifyInfo.selling_price = inputInfo.selling_price;
                        modifyInfo.original_price = inputInfo.original_price;
                        modifyInfo.is_hot_style = inputInfo.is_hot_style;
                        modifyInfo.is_new_style = inputInfo.is_new_style;
                        modifyInfo.is_recommend = inputInfo.is_recommend;
                        modifyInfo.is_bargain = inputInfo.is_bargain;
                        modifyInfo.is_shelves = inputInfo.is_shelves;
                        modifyInfo.sales_volume = inputInfo.sales_volume;
                        modifyInfo.introduction = inputInfo.introduction;
                        modifyInfo.sort = inputInfo.sort;
                        result = con.CommandSet<GoodsInfoEntity>().Update(modifyInfo);

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "修改成功！";
                            AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.GoodsInfoManage, $"修改商品信息，修改信息：{JsonHelper.ToJson(inputInfo)}");
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "修改失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.InvalidOperation;
                        resultInfo.Msg = "对应Id的信息不存在！";
                    }
                    #endregion
                }
                else
                {
                    #region Add
                    var addInfo = inputInfo.MapTo<GoodsInfoEntity>();
                    addInfo.id = GuidHelper.GetGuid();
                    addInfo.create_time = DateTime.Now;
                    result = con.CommandSet<GoodsInfoEntity>().Insert(addInfo);
                    if (result > 0)
                    {

                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "添加成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.GoodsInfoManage, $"添加了一个商品信息，新增信息：{JsonHelper.ToJson(inputInfo)}");
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.InvalidOperation;
                        resultInfo.Msg = "添加失败！";
                    }

                    #endregion
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 是否开启 热卖  推荐  特价  上架 出现的
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> EnableInfo(string id, int type)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var goodsinfo = con.QuerySet<GoodsInfoEntity>().Where(a => a.id == id).Get();
                if (goodsinfo!= null)
                {
                    switch (type)
                    {
                        case 1:
                            goodsinfo.is_hot_style = goodsinfo.is_hot_style == 100 ? 110 : 100;
                            break;
                        case 2:
                            goodsinfo.is_recommend = goodsinfo.is_recommend == 100 ? 110 : 100;
                            break;
                        case 3:
                            goodsinfo.is_bargain = goodsinfo.is_bargain == 100 ? 110 : 100;
                            break;
                        case 4:
                            goodsinfo.is_shelves = goodsinfo.is_shelves == 100 ? 110 : 100;
                            break;
                        default:
                            break;
                    }
                    var result = con.CommandSet<GoodsInfoEntity>().Update(goodsinfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功！";
                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.GoodsInfoManage, $"操作成功，操作数据：{id}-{type}");
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "参数无效！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除商品信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> ids)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //删除
                    var info = tran.QuerySet<GoodsInfoEntity>().Where(p => p.id.In(ids.ToArray())).ToList();
                    info.ForEach(a => a.is_deleted = (int)IsDeleted.Deleted);
                    var result = tran.CommandSet<GoodsInfoEntity>().Update(info);
                    if (result > 0)
                    {
                        con.CommandSet<GoodsPictureEntity>().Where(p => p.goods_id.In(ids.ToArray())).Delete();
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "删除成功！";
                        AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.GoodsInfoManage, $"删除商品信息成功，逻辑删除信息：{JsonHelper.ToJson(ids)}");
                    }
                    else
                    {
                        resultInfo.Msg = "删除失败！";
                    }
                });

            }
            return resultInfo;
        }

        #endregion

        #endregion
    }
}
